﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Marmat.Forms
{
    public class TreeViewEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
            IDesignerHost designerHost = (IDesignerHost)context.GetService(typeof(IDesignerHost));
            if (edSvc is object)
            {
                switch (context.PropertyDescriptor.Name ?? "")
                {
                    case "Nodes":
                        {
                            var frm = new TreeNodeCollectionForm((TreeView)context.Instance);
                            if (frm.ShowDialog() == DialogResult.OK && value is TreeNodeCollection collection)
                            {
                                collection.Clear();
                                foreach (var node in frm.TreeView1.Nodes)
                                    collection.Add(node);
                                context.OnComponentChanged();
                            }

                            break;
                        }

                    default:
                        {
                            MessageBox.Show(context.PropertyDescriptor.Name);
                            break;
                        }
                }
            }

            return value;
        }

        public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        {
            return true;
        }
    }
}